package com.msb.reference;

import com.msb.Worker;

import java.lang.ref.SoftReference;

/**
 * 软依赖：对象没有强依赖，且发生一次gc，且内存不够，才回收
 */
public class SoftReferenceDemo {
    public static void main(String[] args) {
        Worker worker = new Worker();
        SoftReference<Worker> soft = new SoftReference<>(worker);
        System.out.println("worker: "+worker);

        worker = null; //1.没有强依赖

        System.gc(); //2.发生一次gc

        if(soft != null){ //3.内存已满，此条件并没有发生，所以soft不为空
            worker = soft.get();
            System.out.println("soft(gc before): "+worker);
        }else {
            worker = new Worker();
            System.out.println("soft(gc end): "+ worker);
        }
    }

}
